package com.odontosis.view.cheque;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.odontosis.entidade.Recibo;
import com.odontosis.service.ReciboService;
import com.odontosis.util.StringUtilsOdontosis;
import com.odontosis.view.OdontosisAction;

public class AcaoListaCheque extends OdontosisAction<ReciboService> {
	

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws Exception {
		FormListaCheque formulario = (FormListaCheque) form;
		if(StringUtils.isEmpty(formulario.getMetodo()))
		{
			return onIniciarTela(mapping, form, request, response);
		} else if (formulario.getMetodo().equals("pesquisar")) {
			return onPesquisa(mapping, form, request, response);
		} else if (formulario.getMetodo().equals("comentar")) {
			return onComenta(mapping, form, request, response);
		}
		return onIniciarTela(mapping, form, request, response);
		
	}
	
	
	public ActionForward onIniciarTela(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		return mapping.getInputForward();
	}
	
	public ActionForward onComenta(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		FormListaCheque formulario = (FormListaCheque) form;
		Long id = Long.parseLong(formulario.getCodigo());
		if(formulario.getComentario() != null && formulario.getComentario().length() > 300) {
			List<String> errors = new ArrayList<String>();
			errors.add("O comentário deve possuir no máximo 300 caracteres.");
			request.setAttribute("mensagens", errors);
			return mapping.getInputForward();
		}
		
		Recibo recibo = service.load(id);
		recibo.setComentario(formulario.getComentario());
		service.update(recibo);
				
		Collection<String> sucesso = new ArrayList<String>();
		sucesso.add("Comentário inserido com sucesso.");
		request.setAttribute("sucesso", sucesso);
		return onPesquisa(mapping, form, request, response);
	}
	
	public ActionForward onPesquisa(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		FormListaCheque formulario = (FormListaCheque) form;
		Collection<Recibo> colecao = service.buscarCheques(formulario.getResponsavel(), formulario.getBanco(), formulario.getNumero());
		request.setAttribute("colecao", colecao);
		return mapping.getInputForward();
	}
	
	

}

